package com.jeesuite.apigateway;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import com.jeesuite.apigateway.filter.AccessControllerFilter;
import com.jeesuite.apigateway.filter.RequestLimitFilter;
import com.jeesuite.apigateway.filter.ResponseWrapFilter;
import com.jeesuite.apigateway.filter.SwitchEnableCorsFilter;
import com.jeesuite.springboot.starter.cache.EnableJeesuiteCache;

@EnableZuulProxy
@EnableDiscoveryClient
@EnableJeesuiteCache
@SpringCloudApplication
public class ApiGatewayApplication {

	public static void main(String[] args) {

    	
		long starTime = System.currentTimeMillis();
		new SpringApplicationBuilder(ApiGatewayApplication.class).web(true).run(args);
    	
		long endTime = System.currentTimeMillis();
		long time = endTime - starTime;
		System.out.println("\nStart Time: " + time / 1000 + " s");
		System.out.println("...............................................................");
		System.out.println("..................ApiGateway starts successfully..................");
		System.out.println("...............................................................");
	}

	@Bean
	public AccessControllerFilter accessFilter() {
		return new AccessControllerFilter();
	}

	@Bean
	public ResponseWrapFilter responseFilter() {
		return new ResponseWrapFilter();
	}
	
	@Bean
	public RequestLimitFilter reqLimitFilter() {
		return new RequestLimitFilter();
	}

	@Bean
	public SwitchEnableCorsFilter corsFilter() {
		
		final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		final CorsConfiguration config = new CorsConfiguration();
		config.setAllowCredentials(true); // 允许cookies跨域
    	config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.setMaxAge(18000L);
		source.registerCorsConfiguration("/**", config);
		return new SwitchEnableCorsFilter(source);
	}

}
